package com.palm.vue.integration;

import com.palm.vue.VueResourceLoader;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.GZIPOutputStream;

public class CachedScriptHandler implements Handler {
    protected static final Date modified_time = new Date();
    private int maxAge;
    private byte[] data;

    public CachedScriptHandler(String path,int maxAge){
        this.maxAge=maxAge;

        loadData(path);
    }
    @Override
    public void handle(Context ctx) throws Throwable {
        ctx.setHandled(true);
        String modified_since = ctx.header("If-Modified-Since");
        String modified_now = modified_time.toString();
        if (modified_since != null && maxAge > 0 && modified_since.equals(modified_now)) {
            ctx.headerSet("Cache-Control", "max-age=" + maxAge);
            ctx.headerSet("Last-Modified", modified_now);
            ctx.status(304);
        } else {
            if (maxAge > 0) {
                ctx.headerSet("Cache-Control", "max-age=" + maxAge);
                ctx.headerSet("Last-Modified", modified_time.toString());
            }
            ctx.contentType("application/javascript");
            ctx.headerSet("Content-Encoding","gzip");
            ctx.status(200);
            ctx.output(data);
        }
    }
    protected void loadData(String path){
        InputStream in=VueResourceLoader.loadStream(path);
        data=gzip(VueResourceLoader.loadText(in));
    }
    private static byte[] gzip(String text) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
                gzip.write(text.getBytes("UTF-8"));
            }
            return out.toByteArray();
        } catch (IOException e) {
            System.err.println("压缩失败:" + e);
        }
        return null;
    }

}
